import { RefObject } from 'react';
import { ScrollView } from 'react-native';

import { Calender, Dispatch, State } from './types';
import { Data, LessonShowInfo } from '../../../../api/course/getUserCoursePage';
import { CourseApi } from '../../../../api';
import { onPressLesson } from '../../../Course/actions';
import navigator from '../../../../util/navigator';

let dispatch: Dispatch;
let state: State;
let reload = (): void => {};
let scroll: RefObject<ScrollView>;

export default (d: Dispatch, s: State): void => {
  dispatch = d;
  state = s;
};

export const getReload = (): void => {
  reload();
};

export const setScroll = (s: RefObject<ScrollView>): void => {
  scroll = s;
};

export const setData = (value: Data): void => {
  dispatch({ type: 'SET_DATA', value });
};

export const setCurrentDate = (value: Calender): void => {
  dispatch({ type: 'SET_CURRENT_DATE', value });
  if (scroll && scroll.current) {
    scroll.current.scrollTo({
      x: 0,
      y: 0,
      animated: true
    });
  }
};

export const fetchFailed = (): void => {
  dispatch({ type: 'FETCH_FAILED' });
};

// 获取数据
export const getCourseList = async (): Promise<void> => {
  reload = (): void => {
    getCourseList();
  };
  const res = await CourseApi.getUserCoursePage();
  const { code, data } = res;
  if (code !== 0) {
    fetchFailed();
    return;
  }
  setData(data || { courses: [], lessons: [] });
};

// 点击我的课程刷新课程状态
export const clickTodayLesson = async (
  lesson: LessonShowInfo
): Promise<void> => {
  const res = await CourseApi.getUserCoursePage(true);
  const { code, data } = res;
  if (code !== 0) return;
  const { lessons } = data;
  const currentLesson =
    lessons.find((item): boolean => item.id === lesson.id) || lesson;
  onPressLesson({ ...currentLesson, name: lesson.name });
};

export const homeWork = (): void => {
  navigator.push('Correction');
};
